package com.github.byakkili.bim.protocol.json2protobuf.tcp;

import cn.hutool.core.util.ObjectUtil;
import com.github.byakkili.bim.core.handler.command.CommandHandler;
import com.github.byakkili.bim.core.protocol.Protocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * +--------+--------+
 * |  命令  |  JSON  |
 * +--------+--------+
 * |  数字  | 字符串  |
 * +--------+--------+
 *
 * @author Guannian Li
 */
public class TcpJson2protoBufProtocol implements Protocol {
    @Override
    public String name() {
        return "TCP-JsonToProtoBuf";
    }

    @Override
    public boolean canSupport(ByteBuf buffer) {
        buffer.markReaderIndex();
        try {
            return ObjectUtil.equal(buffer.readByte(), TcpJsonToProtoBufPacket.PROTOCOL_HEAD);
        } finally {
            buffer.resetReaderIndex();
        }
    }

    @Override
    public void addPipeline(Channel ch) {
        ch.pipeline()
                // 协议1位, 长度4位, Json bytes
                .addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 1, 4, 0, 5))
                .addLast(TcpJson2protoBufCodec.INSTANCE)
                .addLast(CommandHandler.INSTANCE);
    }
}

